import React, { useState } from 'react';
import NumberField from '../../../components/common/NumberField';
import StatefulCalculationCard from '../../../components/common/StatefulCalculationCard';
import ExportData from '../../../components/common/ExportCalculateData';
import { Card, Typography } from 'antd';
import type { ResultItem } from '../../../../shared/types';

// 测试计算参数类型定义
export interface TestCalculationValues {
  testValue1: number;
}

// 测试计算结果类型定义
export interface TestCalculationResult {
  testResult1: number;
}

// 测试计算初始值配置
const initialValues: TestCalculationValues = {
  testValue1: 1,
};

// 测试计算卡片组件配置
const demoConfig = {
  key: 'TestCalculation',
  label: '测试算法计算',
  formKey: 'demo-1',
  initialValues: initialValues,
  calculationType: 'demo-1',
  resultFormatter: (data: TestCalculationResult) => [
    { key: 'testResult1', name: '计算结果', value: data.testResult1, unit: '' },
  ],
  renderFormFields: () => (
    <>
      <NumberField name="testValue1" label="测试数值" required step={0.001} tooltip="用于测试计算的数值" />
    </>
  ),
    // 优化LaTeX公式格式，确保正确渲染
  optimizedFormula :"q = \gamma_f h_q \\text{，其中 } h_q = 0.45 \\times 2^{S-1} \\times [1 + i \\cdot (B_f - 5)]",
};


// 测试计算卡片组件实现
const DemoCard: React.FC = () => {
  const [lastImported, setLastImported] = useState<any | null>(null);
  const [lastResults, setLastResults] = useState<ResultItem[] | null>(null);

  return (
    <div>
      <StatefulCalculationCard
        title={demoConfig.label}
        formKey={demoConfig.formKey}
        initialValues={demoConfig.initialValues}
        renderFormFields={demoConfig.renderFormFields}
        calculationType={demoConfig.calculationType}
        resultFormatter={(data) => {
          const results = demoConfig.resultFormatter(data);
          setLastResults(results);
          return results;
        }}
        columnCount={1} // 使用1列布局
        tableHeight={300} // 设置表格高度为300px
        formula={demoConfig.optimizedFormula}
        exportComponent={(form) => (
          <ExportData
            siteName={demoConfig.label}
            inputs={form.getFieldsValue()}
            results={lastResults ? Object.fromEntries(lastResults.map(r => [r.key, r.value])) : {}}
            calculationType={demoConfig.calculationType}
          />
        )}
        onAfterReset={(defaults) => {
          // 当重置时把 lastImported 清空或更新为默认值，便于观察
          setLastImported(defaults ?? null);
          setLastResults(null);
        }}
      />

      <Card size="small" style={{ marginTop: 12 }}>
        <Typography.Title level={5}>Demo 导入/重置调试</Typography.Title>
        <div style={{ fontSize: 12, color: '#333' }}>
          <div><strong>最近导入（或重置到默认）:</strong></div>
          <pre style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word', marginTop: 8 }}>{JSON.stringify(lastImported, null, 2)}</pre>
        </div>
      </Card>
    </div>
  );
};

export default DemoCard;